var express = require('express');
var router = express.Router();
var db = require('../data');
var request = require('request');
var encryption = require('encryption');
var access_token = require('./develop/access_token');
var crypto = require('crypto');
/* GET home page. */

var randNum = function (minnum , maxnum){
    return Math.floor(minnum + Math.random() * (maxnum - minnum));
};

var randomString = function(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function sha1(str) {
    var md5sum = crypto.createHash('sha1');
    md5sum.update(str);
    str = md5sum.digest('hex');
    return str;
}

var GET = function(req, res, next){

    console.log(access_token);

    var noncestr = randomString(32);
    var jsapi_ticket = access_token.jsTicket;
    var timestamp = new Date().getTime();
    var url = 'http://'+req.headers.host+req.originalUrl;

    var data = [
        "noncestr="+noncestr,
        "jsapi_ticket="+jsapi_ticket,
        "timestamp="+timestamp,
        "url="+url
    ];

    var signature = data.sort();
    signature = sha1(signature.join('&'));

    data = {
        appid: access_token.appId,
        timestamp: timestamp,
        noncestr: noncestr,
        signature: signature,
        jsApiList: "'onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone','startRecord','stopRecord','onVoiceRecordEnd','playVoice','pauseVoice','stopVoice','onVoicePlayEnd','uploadVoice','downloadVoice','chooseImage','previewImage','uploadImage','downloadImage','translateVoice','getNetworkType','openLocation','getLocation','hideOptionMenu','showOptionMenu','hideMenuItems','showMenuItems','hideAllNonBaseMenuItem','showAllNonBaseMenuItem','closeWindow','scanQRCode','chooseWXPay','openProductSpecificView','addCard','chooseCard','openCard'"
    };

    res.render('index', data);
};

var POST = {
    phone: function(req, res, next){

        var phone = req.body.phone;
        var model = db.model;
        var imei = 'h5_351521004992889';
        var key = 'NKK.ENAZ';

        var param = encryption('{"imei":'+ imei +',"mobile":"'+ phone +'"}', key);

        request.post({url:'http://mobser.fuzhou-air.cn/frontend/service/UserAction_htmlSendSMS', form: {imei: imei, param: param}}, function(err,httpResponse,body){

            if(err)
                res.send({code: 1, msg: "接口访问失败"});
            else{
                res.send(JSON.parse(body));
            }

        });

    },
    code: function(req, res, next){
        var imei = 'h5_351521004992889';
        var key = 'NKK.ENAZ';
        var code = req.body.code;
        var phone = req.body.phone;

        var param = encryption(JSON.stringify({
            userName: phone,
            password: '000000',
            idType  : 'OTHER',
            idNo    : '11',
            mobileNo: phone,
            name    : 'h5_'+phone,
            identifyCode: code
        }), key);
        request.post({url:'http://mobser.fuzhou-air.cn/frontend/service/UserAction_htmlRegist', form: {imei: imei, param: param}}, function(err,httpResponse,body){
            if(err)
                res.send({code: 1, msg: "接口访问失败"});
            else{
                var model = db.model;
                model.user.update({phone: phone}, {$set: {phone: phone, date: new Date().getTime()}}, {upsert: true}, function(err, docs){
                    if(err){
                        res.send({status: 1, msg: "内部错误"});
                    }else{
                        res.send(JSON.parse(body));
                    };
                });
            }
        })
    }
}


router.get('/', GET);
router.get('/index', GET);
router.post('/index/phone', POST.phone);
router.post('/index/code', POST.code);

module.exports = router;
